package com.mars.component.scheduler.utlis.spring;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.quartz.QuartzJobBean;

import com.mars.component.scheduler.entity.SchedulerTask;

public class ScheduleJob extends QuartzJobBean {
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	private ExecutorService service = Executors.newSingleThreadExecutor(); 
	
	@Override
	protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
		SchedulerTask schedulerTask = (SchedulerTask) context.getMergedJobDataMap().get(SchedulerTask.JOB_PARAM_KEY);
		//任务开始时间
        long startTime = System.currentTimeMillis();
		
        try {
            //执行任务
        	logger.info("任务准备执行，任务ID：" + schedulerTask.getJobId() + "  分组名称：" + schedulerTask.getJobGroup() + "  Cron表达式：" + schedulerTask.getCronExpression());
        	
            ScheduleRunnable task = new ScheduleRunnable(
            		schedulerTask.getBeanName(), 
            		schedulerTask.getMethodName(), 
            		schedulerTask.getParams());
            
            Future<?> future = service.submit(task);
            
			future.get();
			
			//任务执行总时长
			long times = System.currentTimeMillis() - startTime;
			
			logger.info("任务执行完毕，任务ID：" + schedulerTask.getJobId() + "  分组名称：" + schedulerTask.getJobGroup() + "  Cron表达式：" + schedulerTask.getCronExpression() + "  总共耗时：" + times + "毫秒");
		} catch (Exception e) {
			//任务执行总时长
			long times = System.currentTimeMillis() - startTime;
			logger.error("任务执行失败，任务ID：" + schedulerTask.getJobId() + "  分组名称：" + schedulerTask.getJobGroup() + "  Cron表达式：" + schedulerTask.getCronExpression() + "  总共耗时：" + times + "毫秒 ", e);
		}finally {
			//TODO
			//记录任务的执行信息到数据库
		}
	}

}
